﻿#!/usr/bin/python
# -*- encoding: utf-8 -*-
'''
@File    : GratisoGraphyWidget.py
@Desc    : 
@Version : 1.0
@Author  : echohelper 
@Email   : echohelper@qq.com
@WebSite : www.github.com/echohelper
@Time    : 2021/12/24 19:16:18
'''
# Start typing your code from here

from urllib import request
from PyQt5 import QtCore, QtGui, QtWidgets

from module.crawler.Ui_GratisoGraphyWidget import Ui_Form

from urllib.parse import urlparse
from urllib.request import *
from time import ctime

class GratisoGraphyWidget(QtWidgets.QWidget):
    
    def __init__(self):
        super().__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.initUi()

    # 初始化界面
    def initUi(self):
        self.ui.btnOpen.clicked['bool'].connect(self.onBtnOpen)
        self.ui.btnPrint.clicked['bool'].connect(self.onBtnPrint)
        self.ui.btnDownload.clicked['bool'].connect(self.onBtnDownload)

    def onBtnOpen(self, checked:bool):
        self.tabCurrentIndexChanged(self.ui.tabWidget.currentIndex)

    def onBtnPrint(self, checked:bool):
        self.urlParse(self.ui.lineEditWebsite.text())

    def onBtnDownload(self, checked:bool):
        url = self.ui.lineEditWebsite.text()
        self.urlParse(url)
        response = request.urlopen(url)
        print(response.read().decode('utf-8'))

    # 解析URL
    def urlParse(self, url:str):
        # urlparse("scheme://netloc/path;parameters?query#fragment")
        # urlparse("http://docs.python.org:80/3/library/urllib.parse.html?highlight=params#url-parsing")
        urlret = urlparse(url)
        self.showMessage("urlret.hostname: ", str(urlret.hostname))
        self.showMessage("urlret.port: ", str(urlret.port))
        self.showMessage("urlret.scheme: ", str(urlret.scheme))
        self.showMessage("urlret.netloc: ", str(urlret.netloc))
        self.showMessage("urlret.path: ", str(urlret.path))
        self.showMessage("urlret.params: ", str(urlret.params))
        self.showMessage("urlret.query: ", str(urlret.query))
        self.showMessage("urlret.fragment: ", str(urlret.fragment))
        self.showMessage("urlret.username: ", str(urlret.username))
        self.showMessage("urlret.password: ", str(urlret.password))
    
    # 标签页切换
    def tabCurrentIndexChanged(self, index:int):
        tabName = self.ui.tabWidget.tabText(self.ui.tabWidget.currentIndex())
        self.showMessage("当前标签名称：", tabName)

    # 打印日志输出
    def showMessage(self, prefix:str, text:str):
        strText = prefix + text
        self.ui.textBrowser.append(strText)
